package com.yupi.yupao.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: Peter
 * @Date: 2024-09-17-18:13
 * @Description: Pe
 */
@ConfigurationProperties(prefix = "config.jwt", ignoreInvalidFields = true)
@Component
@Data
@Slf4j
public class JWTConfig {
    private String secret;//秘钥
    private Long expire;//过期时间
    private String header;//token头部
    private String tokenPrefix;


    /**
     * 创建token
     *
     * @param subject
     * @return
     */
    public String createToken(String subject) {
        //获取当前时间
        Date nowDate = new Date();
        //计算过期时间
        Date expireTime = new Date(System.currentTimeMillis()+expire );
        return tokenPrefix+ JWT.create().withExpiresAt(expireTime).withSubject(subject).sign(Algorithm.HMAC512(secret));

    }

    /**
     * token解密
     * @param token
     * @return
     */
    public DecodedJWT decodedJWT(String token){
        DecodedJWT jwt=null;
        try {
            // 使用了HMAC256加密算法。
            // mysecret是用来加密数字签名的密钥。
            JWTVerifier verifier = JWT.require(Algorithm.HMAC512(secret)).build();// Reusable
            // verifier
            // instance
            token=token.split(" ")[1];
            jwt = verifier.verify(token);
        } catch (JWTVerificationException exception) {
            // Invalid signature/claims
            exception.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jwt;
    }

    public String validateToken(String token) {

        try {
            return JWT.require(Algorithm.HMAC512(secret))
                    .build()
                    .verify(token.replace(tokenPrefix, ""))
                    .getSubject();

        } catch (TokenExpiredException e) {
            log.info("token已过期");
            return "token已过期";
        }catch (Exception e) {
            log.info("token验证失败");
            return "token验证失败";
        }
    }
    /**
     * 检查token是否需要更新
     * @param token ·
     * @return
     */
    public boolean isNeedUpdate(String token) {
        //获取token过期时间
        Date expiresAt = null;
        try {
            expiresAt = JWT.require(Algorithm.HMAC512(secret))
                    .build()
                    .verify(token.replace(tokenPrefix, ""))
                    .getExpiresAt();
        } catch (TokenExpiredException e) {
            return true;
        } catch (Exception e) {
            log.info("token验证失败");
            return false;
        }
        //如果剩余过期时间少于过期时常的一般时 需要更新
        return (expiresAt.getTime() - System.currentTimeMillis()) < (expire >> 1);
    }

}
